<template>
	<view class="p30">
		<view v-if="$validatenull(deviceData)">
			<cust-empty desc="暂无车辆,请前往绑定!" btnText="前往绑定" :showDefaultBtn="true"
				@clickBtn="$navigateTo('/pagesMy/views/addDevice')">
			</cust-empty>
		</view>
		<view v-else>
			<view class="cust-fix-top">
				<view class="flex-align-center" @click="selectBike">
					<text class="f36 bold mr10">{{car.nickName}}</text>
					<u-icon name="xiasanjiaoxing" color="#AAB1C2" size="12" :isShowIcon="false"
						customPrefix="iconfontbike iconbike">
					</u-icon>
				</view>
			</view>
			<view class="h90"></view>

			<view class="common-box">
				<view class="f24 mb20" style="color: #666666;" v-if="car.isAuth!='1'">
					<!-- 您的服务订阅有效期还剩余<text class="c-danger">{{tboxExpireDay}}</text>天，为不影响您的使用，请尽快续费！ -->
					您的服务订阅到期时间为<text class="c-danger">{{tboxExpireDay.split(" ")[0]}}</text>，为不影响您的使用，请尽快续费！
				</view>
				<view class="subscribe-list">
					<view class="tc mr24 small-common-box" v-for="(item, index) in carSubscribeTimeList" :key="index"
						:class="selectIndex==index?'selected':''" @click="selectSubscribeTimeFun(item,index)">
						<view class="mt20 days">订阅 +{{item.dictKey}}天</view>
						<view class="c-danger f28 mt10 price">
							{{unit}}
							{{item.remark}}
						</view>
					</view>
				</view>
				<view class="mt30">
					<u-button :customStyle="{width: '150px'}" type="primary" text="去付费" :throttleTime="1000"
						@click="toPay">
					</u-button>
				</view>
				<view class="flex-center mt30  mb10">
					<u-checkbox activeColor="#06B7F3" size="13" @change="agreeChange">
					</u-checkbox>
					<view class="tc" @click="gotoFun('/pagesMy/views/agreement?title=订阅付费须知')">
						已了解并同意 <text class="c-primary">《订阅付费须知》</text>
					</view>
				</view>
			</view>

			<view>
				<view class="mt30">
					<feedback title="支付记录">
						<template v-slot:content>
							<u-row class="f20">
								<u-col span="4" textAlign="center">付费时间</u-col>
								<u-col span="2" textAlign="center">金额</u-col>
								<u-col span="2" textAlign="center">新增天数</u-col>
								<u-col span="4" textAlign="center">到期时间</u-col>
							</u-row>
							<view class="h10"></view>
							<u-row class="f20" customStyle="margin-top:10rpx;" v-for="item in payRecord" :key="item.id">
								<u-col span="4" textAlign="center" customStyle="font-size:20rpx;">
									{{item.paySucceedTime}}
								</u-col>
								<u-col span="2" textAlign="center" customStyle="font-size:20rpx;color:#EC1010;">
									{{unit}}
									{{item.payableMoney}}
								</u-col>
								<u-col span="2" textAlign="center" customStyle="font-size:20rpx;color:#06B7F3;">
									{{item.buyTime}}
								</u-col>
								<u-col span="4" textAlign="center" customStyle="font-size:20rpx;">
									{{item.tboxBuyAfterExpireTime?item.tboxBuyAfterExpireTime.split(" ")[0]:'-'}}
								</u-col>
							</u-row>
						</template>
					</feedback>
				</view>
			</view>

			<u-action-sheet :actions="bikeList" :props="props" title="选择车辆" :show="show" @select="selectClick"
				round="15" @close="close">
			</u-action-sheet>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import custEmpty from "@/components/cust-empty/index.vue";
	import Feedback from "../components/feedback";
	import {
		getStoreSyncUtil
	} from "@/utils/store.js";
	import {
		getCarListAPI,
		getCarDetailAPI,
		getCarpayRecordList,
		getCarpayRecord,
		getPreorderAPI,

	} from "@/api/api/car.js";
	import {
		getDictBizDataAPI
	} from "@/api/api/my.js";
	import {
		throttle
	} from '@/utils/utils.js'

	export default {
		name: 'subscribe-service',

		components: {
			custEmpty,
			Feedback,
		},

		data() {
			return {
				subscribeTime: "",
				tboxExpireDay: '-', //到期时间
				show: false,
				car: '',
				bikeList: [],
				// currentBike: {},
				props: {
					name: 'nickName'
				},
				selectIndex: '-1',
				unit: '￥',
				carSubscribeTimeList: [],
				payRecord: [],
				isAgree:false
				
			};
		},
		computed: {
			...mapState(["deviceData","loginUser"])
		},
		// onLoad() {
		// 	this.currentBike = getStoreSyncUtil("currentBike");
		// },
		onShow() {
			this.getCarListFun();
			this.$store.commit("setSpecialAppOnShow", false);
			getDictBizDataAPI("car_subscribe_time").then(([err, data2]) => {
				if (err) return;
				this.carSubscribeTimeList = data2;
			});
		},
		watch: {
			car: {
				handler(nval) {
					if (nval) {
						getCarDetailAPI(nval.id).then(([err1, data2]) => {
							if (err1) return;
							console.log(data2);
							if (data2.tboxExpireTime) {
								this.tboxExpireDay = data2.tboxExpireTime;
							}
							// // let timeDiff = (new Date(data2.tboxExpireTime)).getTime()-(new Date()).getTime();
							// if(timeDiff<=0){
							// 	this.tboxExpireDay="已过期";
							// }else{
							// 	// this.tboxExpireDay=Math.ceil(timeDiff / (1000 * 3600 * 24));
							// 	// this.tboxExpireDay=timeDiff / (1000 * 3600 * 24);
							// }
						});
						this.getCarpayRecordListFun(nval.id);
					}
				}
			}
		},
		methods: {
			agreeChange(flag){
				this.isAgree = flag;
			},
			getCarpayRecordListFun(id) {
				getCarpayRecordList({
					carId: id,
					descs: 'create_time',
					customerId: this.loginUser.user_id
				}).then(([err1, data2]) => {
					if (err1) return;
					console.log(data2);
					this.payRecord = data2.records;
				});
			},
			gotoFun: throttle(function(url) {
				this.$navigateTo(url);
			}),
			toPay() {
				if(!this.isAgree){
					this.$showToast('请同意须知');
					return;
				}
				if (this.car.isAuth == "1") {
					this.$showToast('当前车辆未认证');
					return;
				}
				if (this.$validatenull(this.subscribeTime)) {
					this.$showToast('请选择订阅天数');
					return;
				}
				getCarpayRecord({
					// carId: "1630403637096226817",
					carId: this.car.id,
					payableMoney: this.subscribeTime.remark,
					buyTime: this.subscribeTime.dictKey,
					unit: 1,
					payMode: 1,
				}).then(([err, data2]) => {
					if (err) return;
					getPreorderAPI({
						openid: data2.openId,
						payMode: "wx",
						orderAmt: data2.actualMoney,
						shortPayFlag: "yes",
						outTradeNo: data2.payNumber,
						// orderMsg: data2.remark
					}).then(([err, data]) => {
						if (err) return;
						this.$store.commit("setSpecialAppOnShow", true);
						uni.requestPayment({
							provider: 'wxpay',
							appId: data.appId,
							timeStamp: data.timeStamp,
							nonceStr: data.nonceStr,
							package: data.package,
							signType: data.signType,
							paySign: data.paySign,
							success: (res) => {
								this.getCarpayRecordListFun(this.car.id);
								setTimeout(() => {
									if (this.car.id == this.deviceData.id) {
										getCarDetailAPI(this.car.id).then(([err1,
											data2
										]) => {
											if (err1) return;
											this.$store.commit(
												"setDeviceData", {
													...this.deviceData,
													tboxExpireTime: data2
														.tboxExpireTime
												})
											this.tboxExpireTime = data2
												.tboxExpireTime;

										});
									}

								})
							},
							fail: function(err) {
								console.log("err:", err);
								if (err.errMsg == "requestPayment:fail cancel") {
									//util.showModal("取消支付");
								} else {
									//util.showModal(err.errMsg);
								}
							}
						})
					})
				})
			},
			selectSubscribeTimeFun(item, index) {
				console.log("1212", item);
				this.selectIndex = index;
				this.subscribeTime = item;
			},
			selectBike: throttle(function() {
				this.show = true;
			}),
			selectClick(index) {
				this.show = false;
				this.car = index;
			},
			close() {
				this.show = false;
			},
			getCarListFun() {
				getCarListAPI().then(([err, data]) => {
					if (err) return;
					this.bikeList = data.records;
					this.bikeList.forEach((item) => {
						if (item.id == this.deviceData.id) {
							this.car = item;
						}
					})
				})
			},
		}
	}
</script>

<style scoped>
	.subscribe-list {
		display: flex;
		flex-wrap: wrap;
	}

	.small-common-box {
		margin: 12rpx !important;
		min-width: 190rpx !important;
	}
</style>
